<script lang="ts" setup>
import type { CreateTemplateForm } from "../configs/dialogConfigs"
// 模板信息接口
interface TemplateInfo {
  id: string
  name: string
  platform: "抖音" | "小红书"
  workflowId: string
  version: "标准版" | "Pro版" | "Pro Max版"
  createTime: string
}

// 用户信息接口
interface UserInfo {
  id: string
  nickname: string
  phone: string
  userType: 0 | 1 | 2 // 0: 付费用户, 1: 试用中, 2: 试用已过期
  version: 0 | 1 | 2 | 3 // 0: 全部版本, 1: 标准版, 2: Pro版, 3: Pro Max版
}

interface Props {
  modelValue: boolean
  user?: UserInfo
}

interface Emits {
  (e: "update:modelValue", value: boolean): void
}

const props = withDefaults(defineProps<Props>(), {
  user: undefined
})

const emit = defineEmits<Emits>()

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value)
})

// 模拟专属模板数据
const templates = ref<TemplateInfo[]>([
  {
    id: "1",
    name: "火锅店专属探店模板",
    platform: "抖音",
    workflowId: "WF_HOTPOT_CUSTOM_REVIEW",
    version: "Pro版",
    createTime: "2024-08-01"
  },
  {
    id: "2",
    name: "火锅文化传播模板",
    platform: "小红书",
    workflowId: "WF_HOTPOT_CULTURE_POST",
    version: "Pro版",
    createTime: "2024-08-02"
  },
  {
    id: "3",
    name: "餐厅氛围展示模板",
    platform: "抖音",
    workflowId: "WF_RESTAURANT_ATMOSPHERE",
    version: "Pro Max版",
    createTime: "2024-08-03"
  },
  {
    id: "4",
    name: "美食制作过程模板",
    platform: "小红书",
    workflowId: "WF_COOKING_PROCESS",
    version: "标准版",
    createTime: "2024-08-04"
  }
])

// 获取平台标签类型
function getPlatformTagType(platform: string) {
  switch (platform) {
    case "抖音":
      return "danger" // 红色
    case "小红书":
      return "warning" // 橙红色
    default:
      return "info"
  }
}

// 获取版本标签类型
function getVersionTagType(version: string) {
  switch (version) {
    case "标准版":
      return "version-standard" // 灰色
    case "Pro版":
      return "version-pro" // 黑色
    case "Pro Max版":
      return "version-pro-max" // 红色
    default:
      return "version-standard"
  }
}

// 已移除样例预览相关工具函数

// 新增专属模板弹窗状态
const showCreateTemplateDialog = ref(false)

// 处理新增模板
function handleAddTemplate() {
  showCreateTemplateDialog.value = true
}

// 处理模板创建成功
function handleTemplateCreated(template: any) {
  console.log("新增模板:", template)

  // 添加到模板列表
  const newTemplate: TemplateInfo = {
    id: Date.now().toString(),
    name: template.name,
    platform: template.platform,
    workflowId: template.workflowId,
    version: template.version || "Pro版",
    createTime: new Date().toISOString().split("T")[0]
  }

  templates.value.unshift(newTemplate)
  ElMessage.success("专属模板创建成功")
}

// 编辑弹窗状态与当前模板
const showEditTemplateDialog = ref(false)
const editInitialData = ref<Partial<CreateTemplateForm>>({})
const currentEditingId = ref<string | null>(null)

function handleEditTemplate(template: TemplateInfo) {
  editInitialData.value = {
    name: template.name,
    platform: template.platform,
    workflowId: template.workflowId,
    version: template.version
  }
  currentEditingId.value = template.id
  showEditTemplateDialog.value = true
}

function handleEditSuccess(data: CreateTemplateForm) {
  if (!currentEditingId.value) {
    return
  }
  const idx = templates.value.findIndex((t: TemplateInfo) => t.id === currentEditingId.value)
  if (idx > -1) {
    templates.value[idx] = {
      ...templates.value[idx],
      name: data.name,
      platform: data.platform as "抖音" | "小红书",
      workflowId: data.workflowId,
      version: data.version as "标准版" | "Pro版" | "Pro Max版"
    }
    ElMessage.success("模板更新成功")
  }
  showEditTemplateDialog.value = false
  currentEditingId.value = null
}

// 处理删除模板
function handleDeleteTemplate(template: TemplateInfo) {
  ElMessageBox.confirm(
    `确定要删除模板"${template.name}"吗？`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(() => {
    const index = templates.value.findIndex((t: TemplateInfo) => t.id === template.id)
    if (index > -1) {
      templates.value.splice(index, 1)
      ElMessage.success("删除成功")
    }
  }).catch(() => {
    ElMessage.info("已取消删除")
  })
}

// 预览功能已移除
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`配置专属模板 - ${user?.nickname || '用户'}`"
    width="60%"
    custom-class="user-settings-dialog"
    :before-close="() => dialogVisible = false"
  >
    <!-- 弹窗描述 -->
    <div class="dialog-description">
      为VIP商家配置专属的推荐模板，这些模板的优先级高于通用模板。
    </div>

    <!-- 使用 PageHeader 作为内容区域头部 -->
    <PageHeader
      title="专属模板列表"
      subtitle="为该商家配置的专属推荐模板，这些模板的优先级高于通用模板"
      :buttons="[{
        text: '新增专属模板',
        type: 'primary',
        icon: 'Plus',
        onClick: () => handleAddTemplate(),
      }]"
      size="medium"
    />

    <!-- 模板列表表格 -->
    <div class="templates-table">
      <el-table
        :data="templates"
        style="width: 100%"
        class="custom-table"
      >
        <el-table-column prop="name" label="模板名称" min-width="180">
          <template #default="{ row }">
            <div class="template-name">{{ row.name }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="platform" label="适用平台" width="120">
          <template #default="{ row }">
            <CustomTag
              :text="row.platform"
              :type="getPlatformTagType(row.platform)"
              size="small"
            />
          </template>
        </el-table-column>

        <el-table-column prop="workflowId" label="工作流ID" min-width="200">
          <template #default="{ row }">
            <el-tooltip
              :content="row.workflowId"
              placement="top"
              :show-after="500"
              :hide-after="0"
            >
              <div class="workflow-id" :title="row.workflowId">
                {{ row.workflowId }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column prop="version" label="可用套餐" width="140">
          <template #default="{ row }">
            <CustomTag
              :text="row.version"
              :type="getVersionTagType(row.version)"
              size="small"
            />
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="140">
          <template #default="{ row }">
            <div class="create-time">{{ row.createTime }}</div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="140" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <!-- 预览按钮已移除 -->
              <el-button
                link
                size="small"
                type="primary"
                @click="handleEditTemplate(row)"
                title="编辑"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                link
                size="small"
                type="danger"
                @click="handleDeleteTemplate(row)"
                title="删除"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增专属模板弹窗 -->
    <CreateTemplateDialog
      v-model="showCreateTemplateDialog"
      :user="user"
      @success="handleTemplateCreated"
    />

    <!-- 编辑专属模板弹窗（复用新增弹窗 UI，通过 mode 区分） -->
    <CreateTemplateDialog
      v-model="showEditTemplateDialog"
      :user="user"
      mode="edit"
      :initial-data="editInitialData"
      @success="handleEditSuccess"
    />
  </el-dialog>
</template>

<style lang="scss" scoped>
.user-settings-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;

    .el-dialog__header {
      padding: 24px 24px 16px 24px;
      border-bottom: 1px solid var(--el-border-color-extra-light);

      .el-dialog__title {
        font-size: 20px;
        font-weight: 800 !important;
        color: var(--el-text-color-primary);
      }
    }

    .el-dialog__body {
      padding: 24px;
    }
  }
}

.dialog-description {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 24px;
}

// PageHeader 组件样式调整
:deep(.page-header) {
  margin-bottom: 20px;
  padding: 0 0 16px 0;
  border-bottom: 1px solid var(--el-border-color-extra-light);
}

.templates-table {
  .custom-table {
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 8px;
    overflow: hidden;

    :deep(.el-table__header) {
      th {
        background-color: var(--el-fill-color-light);
        color: var(--el-text-color-regular);
        font-weight: 600;
        font-size: 14px;
        padding: 16px 12px;
        border-bottom: 1px solid var(--el-border-color-lighter);
      }
    }

    :deep(.el-table__body) {
      tr {
        &:hover {
          background-color: var(--el-fill-color-light);
        }

        td {
          padding: 16px 12px;
          border-bottom: 1px solid var(--el-border-color-extra-light);
        }
      }
    }
  }

  .template-name {
    font-weight: 500;
    color: var(--el-text-color-primary);
    font-size: 14px;
  }

  .workflow-id {
    font-family: "SF Mono", Monaco, "Cascadia Code", "Roboto Mono", Consolas, "Courier New", monospace;
    font-size: 12px;
    color: var(--el-text-color-secondary);
    background-color: var(--el-fill-color);
    padding: 4px 8px;
    border-radius: 4px;
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      background-color: var(--el-fill-color-light);
      color: var(--el-text-color-regular);
    }
  }

  .file-preview {
    display: flex;
    align-items: center;
    gap: 8px;

    .file-icon {
      font-size: 16px;
      flex-shrink: 0;
    }

    .file-name {
      font-size: 13px;
      color: var(--el-text-color-regular);
      word-break: break-all;
    }
  }

  .no-file {
    color: var(--el-text-color-placeholder);
    font-size: 14px;
  }

  .create-time {
    color: var(--el-text-color-secondary);
    font-size: 13px;
  }

  .action-buttons {
    display: flex;
    gap: 4px;

    .el-button {
      padding: 4px;

      &:hover {
        .el-icon {
          transform: scale(1.1);
        }
      }

      .el-icon {
        font-size: 16px;
        transition: transform 0.2s ease;
      }
    }
  }
}
</style>
